package com.xiaoyu.im.data

import `in`.srain.cube.request.*
import android.util.Log
import com.xiaoyu.base.data.UserKVConfigData
import com.xiaoyu.base.utils.MMKVUtil.Companion.getMultiProcessKV
import com.xiaoyu.im.IMLog.logNetError
import com.xiaoyu.im.config.HttpConfig
import com.xiaoyu.im.datamodel.IMVendorType.IMVendorTypeDef
import com.xiaoyu.im.datamodel.auth.IMTokenInfo
import com.xiaoyu.net.request.RequestWithJsonDataReturn

object IMTokenData {
    @JvmStatic
    fun ensureToken(@IMVendorTypeDef vendorType: String, onFinishListener: Runnable) {
        val logType = "im_token_refresh"

        val request: RequestWithJsonDataReturn<JsonData> = RequestWithJsonDataReturn()
        val requestData: RequestData = request.requestData
        requestData.requestUrl = HttpConfig.IM_TOKEN_REFRESH
        request.requestHandler = object : RequestDefaultHandler<JsonData, JsonData>() {
            override fun processOriginData(originData: JsonData): JsonData {
                return originData.optJson("data")
            }

            override fun onRequestFinish(jsonData: JsonData) {
                val tokenInfo = IMTokenInfo.fromJson(jsonData)
                if (tokenInfo.isEmpty) {
                    val desc = String.format("token is empty, jsonData=%s", jsonData.toString())
                    logNetError(logType, desc)
                } else {
                    saveTokenInfo(vendorType, jsonData)
                }
                onFinishListener.run()
            }

            override fun onRequestFail(failData: FailData) {
                val exception: Exception = failData.exception
                if (exception is CustomNetworkException) {
                    return
                }
                val desc = String.format("request fail, detail=%s", Log.getStackTraceString(exception))
                logNetError(logType, desc)
                onFinishListener.run()
            }
        }
        request.enqueue()
    }

    private fun saveTokenInfo(@IMVendorTypeDef vendorType: String, jsonData: JsonData) {
        val key = UserKVConfigData.KEY_IM_TOKEN_PREFIX + vendorType
        getMultiProcessKV()
                ?.putString(key, jsonData.toString())?.apply()
    }

    @JvmStatic
    fun getTokenInfo(@IMVendorTypeDef vendorType: String): IMTokenInfo {
        val key = UserKVConfigData.KEY_IM_TOKEN_PREFIX + vendorType
        getMultiProcessKV()
                ?.let {
                    val jsonData: JsonData = JsonData.create(it.getString(key, ""))
                    return IMTokenInfo.fromJson(jsonData)
                }
        return IMTokenInfo.EMPTY
    }
}